//定义全局方法。
const cp = {};
var flyEvent;
cp.viewer = null;
cp.viewerDe = null;
cp.labelProvider = null;
cp.imgProvider = null;
cp.geojsonData = {};
cp.currentEntity = null;
cp.currentPolygon = null;
cp.currentPolygonHeight = null;
cp.currentPolygonColor = null;
cp.isOnline = true;
cp.outLineIcenter = "http://219.143.189.234:6633";
cp.inLineIcenter =  "http://192.168.4.120:8310"
//三维球初始化
cp.cesiumInit = function () {
    //使用cesium ion时需要使用key
    Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJiOWI5YjljNy1jMWY0LTRkNTgtYjJkNy05NWMzZmZjYmVhNGMiLCJpZCI6NjE4Niwic2NvcGVzIjpbImFzciIsImdjIl0sImlhdCI6MTU0NTU1OTc1M30.y-BfaFk5W2Kpvdb6k21p42t52qRupO3wexT8Qasz3iI';
    cp.viewer = new GV.GeoCanvas('cesiumContainer', {
        shouldAnimate: true,
        //animation: true,
    });
    window.viewer = cp.viewer;
    //viewer.scene._terrainExaggeration = 2;
    let defaultKey='19b72f6cde5c8b49cf21ea2bb4c5b21e';
    if(cp.isOnline){
        viewer.imageryLayers.remove(viewer.imageryLayers.get(0));//可以先清除默认的第一个影像 bing地图影像。 当然不作处理也行
        var imgUrl="http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles"+"&tk=" + defaultKey;
       
        cp.imgProvider = viewer.imageryLayers.addImageryProvider(
            new Cesium.UrlTemplateImageryProvider({
                url: "http://mt1.google.cn/vt/lyrs=s&hl=zh-CN&x={x}&y={y}&z={z}&s=Gali",
                baseLayerPicker: false
            })
            // new Cesium.WebMapTileServiceImageryProvider({
            //     url: imgUrl,
            //     layer: "tdtBasicLayer",
            //     style: "default",
            //     format: "image/jpeg",
            //     maximumLevel:18, //天地图的最大缩放级别
            //     tileMatrixSetID: "GoogleMapsCompatible",
            //     show: false
            // })
        );
        var labelUrl="http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg"+"&tk="+'19b72f6cde5c8b49cf21ea2bb4c5b21e';
        cp.labelProvider = viewer.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
            url:labelUrl,
            layer: "tdtAnnoLayer",
            style: "default",
            maximumLevel:18,//天地图的最大缩放级别
            format: "image/jpeg",
            tileMatrixSetID: "GoogleMapsCompatible",
            show: false
        }));
        
    }else{
        viewer.imageryLayers.addImageryProvider(new Cesium.WebMapServiceImageryProvider({
            url: `http://10.100.3.55:8310/tilecache/service/wms`,
            layers: 'Global_Image_HBJ-JPEG-4326',
            parameters: {
                format: 'image/JPEG'
            },
            srs: 'EPSG:4326'
        }));
        // viewer.terrainProvider=new Cesium.CesiumTerrainProvider({
        //     url: `http://10.100.3.55:8310/tilecache/service/terrain/Global_DEM_HBJ-TERRAIN-4326`
        // })
    }
    
    const leftClickHandler = new Cesium.ScreenSpaceEventHandler(viewer.canvas)
    const mousemoveHandler = new Cesium.ScreenSpaceEventHandler(viewer.canvas)
    leftClickHandler.setInputAction(function (movement) {
        const pickedObject = viewer.scene.pick(movement.position)
        // ie中通过GraphicLayer加载的对象可以通过该方法拾取
        // const pickedObject = that.viewer.graphicLayer.pickByCoordinate(movement.position.x, movement.position.y)
        if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id) && typeof pickedObject.id.leftClick === 'function') {
            pickedObject.id.leftClick(pickedObject.id)
        } else {
            if(cp.currentPolygon){
                cp.currentPolygon.polygon.extrudedHeight = cp.currentPolygonHeight
                cp.currentPolygon.polygon.material = cp.currentPolygonColor
                cp.currentPolygon = null;
            }
            
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

    // var simpleThrottleFunc = simpleThrottle(mouseMoveEvent, 100, this)
    let timer = null;
    mousemoveHandler.setInputAction(function mouseMove(movement) {
        //const pickedObject = viewer.scene.pick(movement.position)
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            const pickedObject = viewer.scene.pick(movement.endPosition)
            if (Cesium.defined(pickedObject) && Cesium.defined(pickedObject.id) && typeof pickedObject.id.moveMove === 'function') {
                if (cp.currentEntity) {
                    cp.currentEntity.label.show = false;
                    cp.currentEntity = null
                }
                pickedObject.id.moveMove(pickedObject.id)
            } else {
                // const oneDiv = window.document.getElementById("gzinfoBox")
                // oneDiv.style.display = 'none'
                if (cp.currentEntity) {
                    cp.currentEntity.label.show = false;
                    cp.currentEntity = null
                }
            }
        }, 70)

    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

    //结束
}
cp.addBillboard = function (id, position, img, text, type, event) {
    let simplePointEntity = cp.viewer.entities.add({
        id: id, //
        position: Cesium.Cartesian3.fromDegrees(position[0], position[1], 100),
        billboard: {
            image: img,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            //color : Cesium.Color.LIME, // default: WHITE
            width: 20,
            height: 20,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            //scaleByDistance: new Cesium.NearFarScalar(30000, 1, 4000000, 0.2),
        },
        label: {
            text: text,
            show: false,
            font: '14pt Source Han Sans CN', //字体样式
            fillColor: Cesium.Color.BLACK, //字体颜色
            backgroundColor: Cesium.Color.WHITE, //背景颜色
            showBackground: true, //是否显示背景颜色
            outlineColor: Cesium.Color.DARKGOLDENROD,
            style: Cesium.LabelStyle.BLACK, //label样式
            outlineWidth: 1,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            verticalOrigin: Cesium.VerticalOrigin.TOP, //垂直位置
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平位置
            pixelOffset: new Cesium.Cartesian2(0, -70) //偏移
        },
        cursor: true
    })
    simplePointEntity.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND
    if (type && event) {
        simplePointEntity[type] = event
    }
},
cp.addBillboardAndLabel = function (id, position, img, text, type, event) {
    let simplePointEntity = cp.viewer.entities.add({
        id: id, //
        position: Cesium.Cartesian3.fromDegrees(position[0], position[1], 10),
        billboard: {
            image: img,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            //color : Cesium.Color.LIME, // default: WHITE
            width: 31,
            height: 31,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            //scaleByDistance: new Cesium.NearFarScalar(30000, 1, 4000000, 0.2),
        },
        label: {
            text: text,
            show: true,
            font: '14pt Source Han Sans CN', //字体样式
            fillColor: Cesium.Color.BLACK, //字体颜色
            backgroundColor: Cesium.Color.WHITE, //背景颜色
            showBackground: true, //是否显示背景颜色
            outlineColor: Cesium.Color.DARKGOLDENROD,
            style: Cesium.LabelStyle.BLACK, //label样式
            outlineWidth: 1,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            verticalOrigin: Cesium.VerticalOrigin.TOP, //垂直位置
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平位置
            pixelOffset: new Cesium.Cartesian2(0, -60) //偏移
        },
        cursor: true
    })
    simplePointEntity.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND
    if (type && event) {
        simplePointEntity[type] = event
    }
},
cp.addOnlyLabel = function (id, position, height,text, type, event) {
    let simplePointEntity = cp.viewer.entities.add({
        id: id, //
        position: Cesium.Cartesian3.fromDegrees(position[0], position[1], height*1),
        label: {
            text: text,
            show: true,
            font: '15pt Source Han Sans CN', //字体样式
            fillColor: Cesium.Color.AQUA, //字体颜色
            backgroundColor: Cesium.Color.GREY, //背景颜色
            showBackground: true, //是否显示背景颜色
            outlineColor: Cesium.Color.DARKGOLDENROD,
            style: Cesium.LabelStyle.BLACK, //label样式
            outlineWidth: 1,
           // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            verticalOrigin: Cesium.VerticalOrigin.TOP, //垂直位置
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平位置
            pixelOffset: new Cesium.Cartesian2(0, -60) //偏移
        },
        cursor: true
    })
    simplePointEntity.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND
    if (type && event) {
        simplePointEntity[type] = event
    }
},
cp.addBillboard1 = function (id, position, img, text, type, event) {
    let simplePointEntity = cp.viewer.entities.add({
        id: id, //
        position: Cesium.Cartesian3.fromDegrees(position[0], position[1], 100),
        billboard: {
            image: img,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            //color : Cesium.Color.LIME, // default: WHITE
            width: 40,
            height: 60,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            //scaleByDistance: new Cesium.NearFarScalar(30000, 1, 4000000, 0.2),
        },
        label: {
            text: text,
            show: false,
            font: '14pt Source Han Sans CN', //字体样式
            fillColor: Cesium.Color.WHITE, //字体颜色
            backgroundColor: Cesium.Color.DIMGREY, //背景颜色
            showBackground: false, //是否显示背景颜色
            style: Cesium.LabelStyle.FILL, //label样式
            outlineWidth: 2,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            verticalOrigin: Cesium.VerticalOrigin.TOP, //垂直位置
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER, //水平位置
            pixelOffset: new Cesium.Cartesian2(0, -75) //偏移
        },
        cursor: true
    })
    simplePointEntity.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND
    if (type && event) {
        simplePointEntity[type] = event
    }
},
//添加矢量面
cp.addPloygon = function (id, arr, height,i,type,event) {
    var gradient = [];
    function gradientColor(startColor, endColor, step) {
        var startRGB = this.colorRgb(startColor);//转换为rgb数组模式
        var startR = startRGB[0];
        var startG = startRGB[1];
        var startB = startRGB[2];
        var endRGB = this.colorRgb(endColor);
        var endR = endRGB[0];
        var endG = endRGB[1];
        var endB = endRGB[2];
    
        var sR = (endR - startR) / step;//总差值
        var sG = (endG - startG) / step;
        var sB = (endB - startB) / step;
    
        var colorArr = [];
        for (var i = 0; i < step; i++) {
            //计算每一步的hex值 
            var hex = this.colorHex('rgba('+ parseInt((sR * i + startR))+ ',' + parseInt((sG * i + startG))+ ',' + parseInt((sB * i + startB)) + ',.7)');
            colorArr.push(hex);
        }
        gradient = colorArr;
        //return colorArr;
    }
    // 将hex表示方式转换为rgb表示方式(这里返回rgb数组模式)
    gradientColor.prototype.colorRgb = function(sColor) {
        var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        var sColor = sColor.toLowerCase();
        if (sColor && reg.test(sColor)) {
            if (sColor.length === 4) {
                var sColorNew = "#";
                for (var i = 1; i < 4; i += 1) {
                    sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
                }
                sColor = sColorNew;
            }
            //处理六位的颜色值
            var sColorChange = [];
            for (var i = 1; i < 7; i += 2) {
                sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
            }
            return sColorChange;
        } else {
            return sColor;
        }
    };
    // 将rgb表示方式转换为hex表示方式
    gradientColor.prototype.colorHex = function(rgb) {
        var _this = rgb;
        var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        if (/^(rgb|RGB)/.test(_this)) {
            var aColor = _this.replace(/(?:(|)|rgb|RGB)*/g, "").split(",");
            var strHex = "#";
            for (var i = 0; i < aColor.length; i++) {
                var hex = Number(aColor[i]).toString(16);
                hex = hex < 10 ? 0 + '' + hex : hex;// 保证每个rgb的值为2位
                if (hex === "0") {
                    hex += hex;
                }
                strHex += hex;
            }
            if (strHex.length !== 7) {
                strHex = _this;
            }
            return strHex;
        } else if (reg.test(_this)) {
            var aNum = _this.replace(/#/, "").split("");
            if (aNum.length === 6) {
                return _this;
            } else if (aNum.length === 3) {
                var numHex = "#";
                for (var i = 0; i < aNum.length; i += 1) {
                    numHex += (aNum[i] + aNum[i]);
                }
                return numHex;
            }
        } else {
            return _this;
        }
    }
    function rn(min,max){
        return Math.floor(Math.random()*(max-min)+min);
    }
    function rc(){
        // var r = rn(1,152);
        // var g = rn(102,204);
        // var b = rn(0,101);
        var r = rn(76,220);
        var g = rn(73,221);
        var b = rn(38,155);
        return "rgba("+r+','+g+','+b+',.8)';
    }
    new gradientColor('#75e7e9', '#207ab8', 15);
    let simplePointEntity =cp.viewer.entities.add({
        id: id,
        polygon: {
            hierarchy: Cesium.Cartesian3.fromDegreesArray(arr),
            material: Cesium.Color.fromCssColorString(gradient[i]).withAlpha(1),
            extrudedHeight : height
            //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        },
        polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(arr),
            clampToGround: true,
            width: 2,
            material: new Cesium.PolylineOutlineMaterialProperty({
                //color: Cesium.Color.fromCssColorString("#204789"),
                color:  Cesium.Color.DARKTURQUOISE,
                outlineWidth: 1,
                outlineColor: Cesium.Color.BLACK,
            }),
        },
    });
    if (type && event) {
        simplePointEntity[type] = event
    }
}
//添加矢量线
cp.addPloygonLine = function (id, arr, color) {
    cp.viewer.entities.add({
        id: id,
        polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(arr),
            clampToGround: true,
            width: 2,
            material: new Cesium.PolylineOutlineMaterialProperty({
                color: color,
                outlineWidth: 1,
                outlineColor: Cesium.Color.BLACK,
            }),
        },
    });
}
//相机飞行
cp.flyTo = function (x, y, h, heading, pitch, roll) {
    cp.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(x, y, h), // 设置位置
        orientation: {
            heading: heading, // 方向
            pitch: pitch, // 倾斜角度
            roll: roll
        },
    });
}
//获取中心点
cp.getCenter = function () {
    let centerx = (viewer.camera.positionCartographic.longitude * 180) / Math.PI
    let centery = (viewer.camera.positionCartographic.latitude * 180) / Math.PI
    let height = Math.ceil(viewer.camera.positionCartographic.height)
    let heading = viewer.camera.heading
    let pitch = viewer.camera.pitch
    let roll = viewer.camera.roll
    return centerx + ',' + centery + ',' + height + ',' + heading + ',' + pitch + ',' + roll
},

cp.addGeoJsonpolygon = function (url) {
    //Cesium.Math.setRandomNumberSeed(0);
    cp.viewer.scene.globe.depthTestAgainstTerrain = true;
    Cesium.GeoJsonDataSource.load(url, {
        //clampToGround: false, //开启贴地
        stroke: Cesium.Color.fromCssColorString('rgba(115,227,230,1)'),
        strokeWidth: 3,
        fill: Cesium.Color.RED.withAlpha(.3)

    }).then(dataSource => {
        cp.viewer.dataSources.add(dataSource)
        var geocacheEntities = dataSource.entities.values
        console.log(geocacheEntities.length)
        for (var i = 0; i < geocacheEntities.length; i++) {

            var entity = geocacheEntities[i]

            //entity.polygon.heightReference = Cesium.HeightReference.CLAMP_TO_GROUND
            //entity.polygon.extrudedHeightReference= Cesium.HeightReference.CLAMP_TO_GROUND
            //entity.polygon.height = 1000
            entity.polygon.classificationType = Cesium.ClassificationType.TERRAIN
            //console.log(entity.polygon._heightReference)

        }
        cp.geojsonData[url] = dataSource
        cp.viewer.zoomTo(dataSource);
    })

},

cp.removeDataSource = function (url) {
    if (url) {
        cp.viewer.dataSources.remove(cp.geojsonData[url])
        cp.geojsonData[url] = null
    }
},

// 放大功能 
cp.zoomIn = function () {
    let zoomIn = true;
    setTimeout(function () { zoomIn = false; }, 500);
    cp.viewer.clock.onTick.addEventListener(clock => {
        var camera = cp.viewer.camera;
        var ellipsoid = cp.viewer.scene.globe.ellipsoid;
        var cameraHeight = ellipsoid.cartesianToCartographic(
            camera.position
        ).height;
        var moveRate = cameraHeight / 30.0;
        if (zoomIn) {
            camera.moveForward(moveRate);
        }
    });
}
// 缩小功能
cp.zoomOut = function () {
    let zoomOut = true;
    setTimeout(function () { zoomOut = false; }, 500);
    cp.viewer.clock.onTick.addEventListener(clock => {
        var camera = cp.viewer.camera;
        var ellipsoid = cp.viewer.scene.globe.ellipsoid;
        var cameraHeight = ellipsoid.cartesianToCartographic(
            camera.position
        ).height;
        var moveRate = cameraHeight / 30.0;
        if (zoomOut) {
            camera.moveBackward(moveRate);
        }
    });
}
// 复位功能
cp.reset = function () {
    cp.viewer.camera.flyHome()
}
//************************************************** */
//显示或隐藏地形 
cp.showGaocheng = function (isShow) {
    if (isShow) {
        var urlon = "https://www.supermapol.com/realspace/services/3D-stk_terrain/rest/realspace/datas/info/data/path";
        cp.viewer.terrainProvider = new Cesium.CesiumTerrainProvider({
            url: urlon,
            requestVertexNormals: true,
            requestWaterMask: true //水波纹
        });
    } else {
        cp.viewer.terrainProvider = new Cesium.EllipsoidTerrainProvider({
            ellipsoid: Cesium.Ellipsoid.WGS84,
        });
    }
}
cp.option=function(x, y, h, heading, pitch, roll,timer=5) {
    return {
        destination: Cesium.Cartesian3.fromDegrees(x, y, h),
        orientation: {
            heading,
            pitch,
            roll
        },
        duration: timer,
    }
}
cp.initCesiumView=function(x, y, h, heading, pitch, roll) {
    //银河系
    viewer.scene.camera.setView({
        // 初始化相机经纬度
        destination: new Cesium.Cartesian3.fromDegrees(x, y, h),
        orientation: {
            heading,
            pitch, //从上往下看为-90
            roll
        }
    })
}



//统一导出该模块，包含方法和所需变量
export default cp;